# coding=utf-8

"""
    Created by Kalyter on 2017-12-31.
"""

from learning.scientifc import computer, writer
from learning.scientifc.jobs.job import Job
from learning.scientifc.readers import reader


class CompareJob(Job):
    def __init__(self, app):
        super().__init__(app)
        self._max_comparision = app.config.get('MAX_COMPARISION')
        self._jaccard_step = app.config.get('JACCARD_STEP', 5)
        self._compare_path = app.config.get('COMPARE_PATH')

    def run(self):
        path_list = [i for i in reader.read_path(self._compare_path, self._max_comparision)]
        data = []
        pre_data = {}
        tails = ('相似度',)

        files_rank = []
        for filename in path_list:
            tmp_info, tmp_file = reader.read(filename)
            tmp_date = tmp_info[u'日期']
            files_rank.append({
                'filename': filename,
                'date': tmp_date
            })

        files_rank.sort(key=lambda x: x['date'])

        for x in range(len(files_rank) - 1):
            x_filename = files_rank[x]['filename']
            x_info, x_file = reader.read(x_filename)
            if not data:
                compare_title = tuple('比较文件:' + k for k, v in x_info.items())
                compared_title = tuple('被比较文件:' + k for k, v in x_info.items())
                data.append(compare_title + compared_title + tails)

            single_data = []

            for y in range(x + 1, len(files_rank)):
                row = ()
                if y == x + 1:
                    row += tuple(v for k, v in x_info.items())
                else:
                    row += ('',) * len(x_info)
                y_filename = files_rank[y]['filename']
                y_info, y_file = reader.read(y_filename)
                result = computer.compare_by_jaccard(x_file, y_file, self._jaccard_step)
                print('%s   %s  相似度     %.4f' % (x_filename, y_filename, result))
                row += tuple(v for k, v in y_info.items())
                single_data.append(row + (result,))

            single_title = single_data[0][:4]
            single_data.sort(key=lambda x: x[7])
            single_data[0] = single_title + single_data[0][4:]

            pre_data[single_title] = single_data

        sorted_keys = sorted(pre_data.keys(), key=lambda x: x[3])
        for key in sorted_keys:
            data.extend(pre_data.pop(key))

        writer.write(data)
